﻿using Unity.Netcode;
using UnityEngine;

public class CollisionAvoidance : MonoBehaviour
{
    [Header("检测参数")]
    public float minDistance = 1.2f; // 最小允许间距
    public LayerMask targetLayers = 1 << 7;   // 检测的目标层级

    private Collider2D myCollider;

    void Start()
    {
        if (!NetworkManager.Singleton.IsServer)
            Destroy(this);
        
        myCollider = GetComponent<Collider2D>();
    }

    void FixedUpdate()
    {                
        // 检测周围物体
        Collider2D[] nearbyColliders = Physics2D.OverlapCircleAll(
            transform.position,
            minDistance,
            targetLayers
        );

        foreach (Collider2D otherCollider in nearbyColliders)
        {
            // 排除自身
            if (otherCollider == myCollider) continue;

            // 计算间距
            Vector2 direction = transform.position - otherCollider.transform.position;
            float distance = direction.sqrMagnitude;

            // 若距离过近，推开物体
            if (distance <= minDistance*minDistance)
            {
                Vector2 separationForce = direction.normalized * (minDistance - distance);
                // 随机扰动：当多个物体相互靠近时，可能陷入“振动”状态。可添加微小随机偏移打破平衡：
                separationForce += Random.insideUnitCircle * 0.1f;

                otherCollider.transform.position -= (Vector3)separationForce * Time.deltaTime;
            }
        }
    }
}
